package application.ratt.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import android.content.SharedPreferences;
import application.ratt.city_model.City;
import application.ratt.search_alg.RouteNodeInformation;

public class WriteFormattedXml{
	DocumentBuilderFactory docFactory = null;
	DocumentBuilder docBuilder = null;
	Document doc = null;
	Element rootElement = null;
	Element route = null;
	
	public WriteFormattedXml() throws ParserConfigurationException {
		// TODO Auto-generated constructor stub
		docFactory = DocumentBuilderFactory.newInstance();
		docBuilder = docFactory.newDocumentBuilder();
		doc = docBuilder.newDocument();
	}
	
	public void createXMLHeader(){
		// root element
	    rootElement = doc.createElement("results");
	    doc.appendChild(rootElement);
	}
	
	private void createRouteElement(){
		// route element
	    route = doc.createElement("route");
	    rootElement.appendChild(route);
	}
	
	private void createXMLContent(String stationName, String lineName, String stationTime)
	  {
	    // station element
	    Element station = doc.createElement("station");
	    route.appendChild(station);
	 
	    // station name element
	    Element sName = doc.createElement("name");
	    sName.appendChild(doc.createTextNode(stationName));
	    station.appendChild(sName);
	    
	    // station line element
	    Element sLine = doc.createElement("line");
	    sLine.appendChild(doc.createTextNode(lineName));
	    station.appendChild(sLine);
	 
	    // station time element
	    Element sTime = doc.createElement("time");
	    sTime.appendChild(doc.createTextNode(stationTime));
	    station.appendChild(sTime);
	  }
	
	public void writeXMLFile(File cachedDataFile) throws TransformerException, IOException{
		// write xml to file
	    TransformerFactory transformerFactory = TransformerFactory.newInstance();
	 
	    Transformer transformer = transformerFactory.newTransformer();
	    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
	    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2");
	 
	    DOMSource source = new DOMSource(doc);
	 
	    // Show output on console during development
	    // StreamResult result = new StreamResult(System.out);
	    cachedDataFile.getParentFile().mkdirs();
		try{
			cachedDataFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(cachedDataFile);
            StreamResult result = new StreamResult(fos);
    	    transformer.transform(source, result);
            fos.flush();
            fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
	    
	    System.out.println("Xml File saved!");
	}
	
	public void writeRoute(ArrayList<RouteNodeInformation> path, City city, File cachedDataFile, SharedPreferences settings){

		createRouteElement();
		for (RouteNodeInformation s : path) {
			if (s.getNodeId().equals("0")) {
				String[] text = settings.getString("currentLocationAutoText", "").split(",");
				createXMLContent(text[0], "", "-1");
			} else if (s.getNodeId().equals("1")) {
				String[] text = settings.getString("desiredDestinationAutoText", "").split(",");
				createXMLContent(text[0], "walk", Integer.toString(Math.round(s.getTime() / 60)));
			} else {
				if (s.getTransportMode().equals("w")) {
					createXMLContent(city.getStationById(s.getNodeId()).getShortName(), "walk", Integer.toString(Math.round(s.getTime() / 60)));
				} else {
					createXMLContent(city.getStationById(s.getNodeId()).getShortName(),
							city.getLineById(s.getTransportMode()).getName(), Integer.toString(Math.round(s.getTime() / 60)));
				}
			}
		}
	}
}
